package com.lorizz.docrepo.model.impl;

import java.util.Calendar;

import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import com.lorizz.docrepo.DocrepoException;
import com.lorizz.docrepo.model.Folder;
import com.lorizz.docrepo.model.Item;
import com.lorizz.docrepo.repository.impl.JcrUtils;

public abstract class ItemImpl implements Item {

    private static final long serialVersionUID = 1L;
    
    protected Node node;
    protected Session session;

    @Override
    public Calendar getCreated() {
        return JcrUtils.nullSafeGetPropertyValue(node, Property.JCR_CREATED,
                PropertyType.DATE);
    }

    @Override
    public String getCreatedBy() {
        return JcrUtils.nullSafeGetPropertyValue(node, Property.JCR_CREATED_BY,
                PropertyType.STRING);
    }

    @Override
    public String getDescription() {
        return JcrUtils.nullSafeGetPropertyValue(node,
                Property.JCR_DESCRIPTION, PropertyType.STRING);
    }

    @Override
    public String getName() {
        try {
            return this.node.getName();
        } catch (RepositoryException e) {
            throw new DocrepoException(e);
        }
    }

    @Override
    public String getTitle() {
        return JcrUtils.nullSafeGetPropertyValue(node, Property.JCR_TITLE,
                PropertyType.STRING);
    }

    @Override
    public void setDescription(String description) {
        try {
            node.setProperty(Property.JCR_DESCRIPTION, description);
        } catch (Exception e) {
            throw new DocrepoException(e);
        }
    }

    @Override
    public void setTitle(String title) {
        try {
            node.setProperty(Property.JCR_TITLE, title);
        } catch (Exception e) {
            throw new DocrepoException(e);
        }
    }

    @Override
    public String getUuid() {
        try {
            return node.getIdentifier();
        } catch (RepositoryException e) {
            throw new DocrepoException(e);
        }
    }

    public Node getNode() {
        return node;
    }

    public Session getSession() {
        return session;
    }

    public Folder getParent() {
        try {
            if (node.getParent() == null)
                return null;
            return new FolderImpl(node.getParent());
        } catch (RepositoryException e) {
            throw new DocrepoException(e);
        }
    }

    @Override
    public void remove() {
        try {
            node.remove();
        } catch (RepositoryException e) {
            throw new DocrepoException(e);
        }
    }

}
